package com.tang.thread_test;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author tmh
 * @date 2024/3/28 21:14
 * @description
 */
public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor executor=new ThreadPoolExecutor(10,20,0, TimeUnit.SECONDS,new LinkedBlockingDeque<>(1024));
        final int taskCount=5;
        CountDownLatch countDownLatch=new CountDownLatch(taskCount);
        for(int i = 0;i <taskCount ;i++){
            final int finalI=i;
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    int sleepTime=new Random().nextInt(5);
                    try {
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }finally {
                        System.out.println(String.format("task %d over",finalI));
                    }
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        System.out.println("所有线程全部执行完成");
    }
}
